<template>
  <div class="user-container">
    
    <!-- Search row with improved layout -->
    <div class="search-row">
      <span class="search-label">用户名：</span>
      <el-input v-model="user_name" size="small" class="search-input" />
      <span class="search-label">部门：</span>
      <el-select v-model="dept_id" size="small" placeholder="部门" class="search-select">
        <el-option  
          v-for="item in options" 
          :key="item.dept_id" 
          :label="item.dept_name"
          :value="item.dept_id" 
        />
      </el-select>
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 10px 0" />

    <!-- Table container with original layout -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        stripe 
        border 
        style="width: 100%"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold'
        }"
      >
        <el-table-column prop="user_account" label="用户名" />
        <el-table-column prop="user_name" label="真实姓名" />
        <el-table-column prop="user_sex" label="性别">
          <template #default="scope">
            {{ sexValue(scope.row.user_sex) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.userId)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-wrapper">
        <el-pagination 
          v-model:current-page="currentPage" 
          v-model:page-size="pageSize" 
          :page-sizes="[5, 10, 20, 50]"
          :background="true" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="pageCount"
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" size="small"
        />
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <el-dialog v-model="dialogVisible1" title="删除用户信息" width="500px">
      <span>确定删除该条用户信息吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="close1">取消</el-button>
          <el-button type="danger" size="small" @click="del">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Add User Drawer -->
    <el-drawer 
      v-model="dialogVisible" 
      title="添加用户信息" 
      :direction="direction" 
      size="40%"
      @close="close"
    >
      <el-form 
        ref="ruleFormRef" 
        :model="user" 
        :rules="rules"
        label-width="80px"
        class="compact-form"
      >
        <div class="form-columns">
          <div class="form-column">
            <el-form-item prop="user_name" label="真实姓名">
              <el-input v-model="user.user_name" placeholder="真实姓名" />
            </el-form-item>
            
            <el-form-item label="部门" prop="dept_id">
              <el-select v-model="user.dept_id" placeholder="部门">
                <el-option 
                  v-for="item in options" 
                  :key="item.dept_id" 
                  :label="item.dept_name"
                  :value="item.dept_id" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item prop="user_account" label="用户名">
              <el-input v-model="user.user_account" placeholder="用户名" />
            </el-form-item>
            
            <el-form-item prop="user_phone" label="电话">
              <el-input v-model="user.user_phone" placeholder="电话" />
            </el-form-item>
          </div>
          
          <div class="form-column">
            <el-form-item label="性别" prop="user_sex">
              <el-select v-model="user.user_sex" placeholder="性别">
                <el-option 
                  v-for="item in sexOptios" 
                  :key="item.dict_value" 
                  :label="item.dict_label"
                  :value="item.dict_value" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item prop="role_id" label="角色">
              <el-select v-model="user.role_id" placeholder="角色">
                <el-option 
                  v-for="item in rolesOptios" 
                  :key="item.role_id" 
                  :label="item.role_name"
                  :value="item.role_id" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item prop="user_pwd" label="密码">
              <el-input v-model="user.user_pwd" placeholder="密码" type="password" show-password />
            </el-form-item>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <div class="drawer-footer">
          <el-button size="small" @click="close">取消</el-button>
          <el-button type="primary" size="small" @click="userAdd">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- Edit User Drawer -->
    <el-drawer 
      v-model="dialogVisible2" 
      title="修改用户信息" 
      :direction="direction" 
      size="40%"
      @close="close"
    >
      <el-form 
        ref="ruleFormRef" 
        :model="user" 
        :rules="rules"
        label-width="80px"
        class="compact-form"
      >
        <div class="form-columns">
          <div class="form-column">
            <el-form-item prop="user_name" label="真实姓名">
              <el-input v-model="user.user_name" placeholder="真实姓名" />
            </el-form-item>
            
            <el-form-item label="部门" prop="dept_id">
              <el-select v-model="user.dept_id" placeholder="部门">
                <el-option 
                  v-for="item in options" 
                  :key="item.dept_id" 
                  :label="item.dept_name"
                  :value="item.dept_id" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item prop="user_account" label="用户名">
              <el-input v-model="user.user_account" placeholder="用户名" readonly />
            </el-form-item>
          </div>
          
          <div class="form-column">
            <el-form-item label="性别" prop="user_sex">
              <el-select v-model="user.user_sex" placeholder="性别">
                <el-option 
                  v-for="item in sexOptios" 
                  :key="item.dict_value" 
                  :label="item.dict_label"
                  :value="item.dict_value" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item prop="role_id" label="角色">
              <el-select v-model="user.role_id" placeholder="角色">
                <el-option 
                  v-for="item in rolesOptios" 
                  :key="item.role_id" 
                  :label="item.role_name"
                  :value="item.role_id" 
                />
              </el-select>
            </el-form-item>
            
            <el-form-item prop="user_phone" label="电话">
              <el-input v-model="user.user_phone" placeholder="电话" />
            </el-form-item>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <div class="drawer-footer">
          <el-button size="small" @click="close">取消</el-button>
          <el-button type="primary" size="small" @click="userUpdate">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export default {
  setup() {
    const tableData = ref([])
    const user_name = ref("")
    const dept_id = ref("0")
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const options = ref([])
    const rolesOptios = ref([])
    const sexOptios = ref([])
    const dialogVisible = ref(false)
    const dialogVisible1 = ref(false)
    const dialogVisible2 = ref(false)
    const user_id = ref("0")
    const title = ref("添加用户信息")
    const direction = ref('rtl')
    const ruleFormRef = ref(null)

    const user = reactive({
      user_id: "0",
      user_name: "",
      user_account: "",
      user_pwd: "",
      role_id: "",
      user_phone: "",
      user_sex: "",
      dept_id: ""
    })

    const rules = reactive({
      user_name: [
        { required: true, message: "用户名不能为空", trigger: ["blur","change"] }
      ],
      user_account: [
        { required: true, message: "真实姓名不能为空", trigger: ["blur","change"] }
      ],
      user_pwd: [
        { required: true, message: "密码不能为空", trigger: ["blur","change"] }
      ],
      user_phone: [
        { required: true, message: "电话不能为空", trigger: ["blur","change"] }
      ],
      role_id: [
        { required: true, message: "角色不能为空", trigger: ["blur","change"] }
      ],
      dept_id: [
        { required: true, message: "部门不能为空", trigger: ["blur","change"] }
      ],
      user_sex: [
        { required: true, message: "性别不能为空", trigger: ["blur","change"] }
      ]
    })

    onMounted(() => {
      getSex()
      deptOpt()
      getRoles()
      fill()
      count()
    })

    function fill() {
      axios.get("http://localhost:5181/api/User/GetSys_Users", {
        params: {
          name: user_name.value,
          dept_id: dept_id.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        tableData.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/User/GetSys_UsersCount", {
        params: {
          name: user_name.value,
          dept_id: dept_id.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function deptOpt() {
      axios.get("http://localhost:5181/api/Dept/DeptOpt", {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        options.value = [
          { dept_id: '0', dept_name: '请选择部门' },
          ...result.data
        ]
      }).catch((err) => {
        console.error(err)
      })
    }

    function getRoles() {
      axios.get("http://localhost:5181/api/Roles/GetRolesFill", {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        rolesOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function getSex() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "sys_user_sex"
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        sexOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function sexValue(row) {
      if (!row) return "无"
      const sex = sexOptios.value.find((item) => item.dict_value == row)
      return sex ? sex.dict_label : "无"
    }

    function query() {
      fill()
    }

    function reset() {
      user_name.value = ""
      dept_id.value = "0"
      query()
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function addEdit() {
      title.value = "添加用户信息"
      dialogVisible.value = true
    }

    function handleEdit(row) {
      title.value = "修改用户信息"
      Object.assign(user, row)
      dialogVisible2.value = true
    }

    function handleDelete(id) {
      user_id.value = id
      dialogVisible1.value = true
    }

    function close() {
      dialogVisible.value = false
      dialogVisible2.value = false
      user.user_id = "0"
      user.user_name = ""
      user.user_account = ""
      user.user_pwd = ""
      user.role_id = ""
      user.user_phone = ""
      user.user_sex = ""
      user.dept_id = ""
    }

    function close1() {
      dialogVisible1.value = false
      user_id.value = "0"
    }

    function del() {
      axios.put("http://localhost:5181/api/User/Sys_UserDelete", {
        user_id: user_id.value,
        del_flag: '1'
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        if (result.data > 0) {
          ElMessage.success('删除成功')
          fill()
          count()
          close1()
        }
      }).catch((err) => {
        console.error(err)
      })
    }

    function userAdd() {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          axios.post("http://localhost:5181/api/User/Sys_UserAdd", {
            user_name: user.user_name,
            user_account: user.user_account,
            user_pwd: user.user_pwd,
            user_phone: user.user_phone,
            user_sex: user.user_sex,
            dept_id: user.dept_id,
            del_flag: '0',
            create_by: localStorage.getItem('userLName'),
            create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((result) => {
            if (result.data != 0 && result.data != "") {
              return userRolesAdd(result.data)
            } else {
              ElMessage.error('用户信息添加失败')
              return Promise.reject(new Error('用户信息添加失败'))
            }
          }).then((res) => {
            if (res > 0) {
              ElMessage.success('用户信息添加成功')
              fill()
              count()
              close()
            } else {
              ElMessage.warning('用户角色关联失败')
            }
          }).catch((err) => {
            console.error(err)
          })
        }
      })
    }

    function userUpdate() {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          axios.put("http://localhost:5181/api/User/Sys_UserUpdate", {
            user_id: user.user_id,
            user_name: user.user_name,
            user_phone: user.user_phone,
            user_sex: user.user_sex,
            dept_id: user.dept_id,
            update_by: localStorage.getItem('userLName'),
            update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((updateResult) => {
            return userRolesDel(updateResult.data)
              .then(() => userRolesAdd(updateResult.data))
          }).then(() => {
            ElMessage.success('修改成功')
            fill()
            count()
            close()
          }).catch((err) => {
            console.error(err)
            ElMessage.error('操作失败')
          })
        }
      })
    }

    function userRolesDel(userid) {
      return axios.delete("http://localhost:5181/api/Roles/UserRolesRemove", {
        params: { user_id: userid },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => result.data)
    }

    function userRolesAdd(userid) {
      return axios.post("http://localhost:5181/api/Roles/UserRolesAdd", {
        user_id: userid,
        role_id: user.role_id
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => result.data)
    }

    return {
      tableData, user_name, dept_id, currentPage, pageSize, pageCount,
      dialogVisible, dialogVisible1, dialogVisible2, user_id, title, direction,
      options, rolesOptios, sexOptios, user, rules, ruleFormRef,
      query, reset, handleSizeChange, handleCurrentChange, sexValue,
      addEdit, handleEdit, handleDelete, del, close, close1,
      userAdd, userUpdate
    }
  }
}
</script>

<style scoped>
.user-container {
  padding: 15px;
}

.user-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: -3px;
  margin-top: -45px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.search-select {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

.table-container {
  margin-top: 15px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}

.compact-form {
  padding: 20px;
}

.form-columns {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.form-column {
  flex: 1;
}

.drawer-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* Original table styling */
:deep(.el-table) {
  border: 1px solid #ebeef5;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: bold;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
  border-right: none;
  border-bottom: none;
}

:deep(.el-table--border td, .el-table--border th) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table--border::after, .el-table--group::after) {
  background-color: #ebeef5;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}
</style>